/**
 * 表格格式化数据
 * @des {
 *     目前仅明细表使用
 * }
 * */
import { $each } from '../index';
import { isEmptyArr, isNullOrEmpty } from '../is';
import { handleDetailTableConditions } from '../conditionFormat/useConditionFormat.js';
import { cloneDeep } from 'lodash-es';

/**
 * 空对象判断
 */
export function $isEmptyObject(obj) {
  for (const _name in obj) {
    return false;
  }
  return true;
}

/**
 * 处理第二层以下sub动态数据
 * */
function dealDynamicSubData(parentKey, list, subSumArr, subItems, sourceColumns) {
  subSumArr.push(list.length);
  for (let i = 0, len = list.length; i < len; i++) {
    const _subKeys = Object.keys(list[i]);
    const subKeys = [];
    for (let k = 0, kl = _subKeys.length; k < kl; k++) {
      if (sourceColumns.indexOf(_subKeys[k]) != -1) {
        subKeys.push(_subKeys[k]);
      }
    }
    const hasSubKeys = [];
    const subItem = {};
    for (let j = 0, k = subKeys.length; j < k; j++) {
      const key = subKeys[j];
      if (Array.isArray(list[i][key]) && list[i][key].length > 0) {
        const temItem = list[i][key][0];
        if ('url' in temItem && 'type' in temItem) {
          const curkey = parentKey ? `${parentKey}•${key}` : key;
          subItem[curkey] = list[i][key];
        } else {
          // 三层以下数据暂未处理--需要完善
          hasSubKeys.push(key);
          const curkey = parentKey ? `${parentKey}•${key}` : key;
          const subsubItems = [];
          dealDynamicSubData(curkey, list[i][key], subSumArr, subsubItems);
          subItem[curkey] = list[i][key]; // subsubItems;
        }
        
      } else {
        const curkey = parentKey ? `${parentKey}•${key}` : key;
        subItem[curkey] = list[i][key];
      }
    }
    subItems.push(subItem);
  }
}
// 处理第一层动态数据
export function dealDynamicOneData(list, sourceColumns) {
  const columnRowSpanMap = {};
  const _list = [];
  if (list.length > 0) {
    let order = 0;
    for (let i = 0, len = list.length; i < len; i++) {
      const item = list[i];
      const subItems = [];
      if (!$isEmptyObject(item)) {
        const keys = Object.keys(item);
        if (keys.length) {
          // 第一层遍历
          const hasSubKeys = [];
          const _item = {};
          const subSumArr = [1];
          for (let j = 0, k = keys.length; j < k; j++) {
            const key = keys[j];
            if (Array.isArray(item[key]) && item[key].length > 0) {
              const temItem = item[key][0];
              if ('url' in temItem && 'type' in temItem) {
                _item[key] = item[key];
              } else {
                hasSubKeys.push(key);
                const subItems = [];
                dealDynamicSubData(key, item[key], subSumArr, subItems, sourceColumns);
                _item[key] = subItems;
              }
            } else {
              if (Array.isArray(item[key]) && item[key].length <= 0) {
                _item[key] = [''];
              } else {
                _item[key] = [item[key]];
              }
            }
          }
          // 处理合并
          const subSum = Math.max(...subSumArr);
          for (let m = 0; m < subSum; m++) {
            const curItem = {};
            const newKeys = ['key', ...keys, 'operation'];
            for (let j = 0, k = newKeys.length; j < k; j++) {
              const key = newKeys[j];
              // 记录序号、操作列 rowSpan
              if (['key', 'operation'].includes(key)) {
                if (!columnRowSpanMap[key]) {
                  columnRowSpanMap[key] = [];
                }
                if (m == 0) {
                  columnRowSpanMap[key][order + m] = subSum;
                } else {
                  columnRowSpanMap[key][order + m] = 0;
                }
              } else {
                if (!hasSubKeys.includes(key)) {
                  if (!columnRowSpanMap[key]) {
                    columnRowSpanMap[key] = [];
                  }
                  if (m == 0) {
                    columnRowSpanMap[key][order + m] = subSum;
                  } else {
                    columnRowSpanMap[key][order + m] = 0;
                  }
                  const temItem = _item[key][0];
                  if (
                    temItem &&
                    typeof temItem == 'object' &&
                    'url' in temItem &&
                    'type' in temItem
                  ) {
                    curItem[key] = _item[key];
                  } else {
                    curItem[key] = temItem;
                  }
                } else {
                  // 注意为空的情况
                  const curSubItmes = _item[key][0];
                  const subItems = _item[key][m];
                  if (!$isEmptyObject(curSubItmes)) {
                    const subKeys = Object.keys(curSubItmes);
                    for (let n = 0, ll = subKeys.length; n < ll; n++) {
                      const _key = subKeys[n];
                      if (!columnRowSpanMap[_key]) {
                        columnRowSpanMap[_key] = [];
                      }
                      columnRowSpanMap[_key][order + m] = 1;
                      curItem[_key] = $isEmptyObject(subItems) ? '' : subItems[_key];
                    }
                  }
                }
              }
            }
            subItems.push(curItem);
          }
          order += subSum;
        }
      }
      _list.push(...subItems);
    }
  }
  return {
    list: _list,
    columnRowSpanMap,
  };
}
// 解析column多维嵌套children====
const parseDimensionsItem = (sortInfo, item, columns, multiple) => {
  if (item.indexOf('•') != -1) {
    let _columns = columns;
    const itemArr = item.split('•');
    let parItem = {
      title: itemArr[0],
      children: [],
    };
    const leafItem = {
      title: itemArr[itemArr.length - 1],
      dataIndex: item,
      key: item,
    };
    if (multiple != undefined && typeof multiple === 'number') {
      if (!isNullOrEmpty(sortInfo[item])) {
        multiple++;
        leafItem.sorter = {
          multiple,
        };
        leafItem.sortOrder = sortInfo[item];
      }
    }
    for (let i = 0, len = itemArr.length - 1; i < len; i++) {
      const subIiem = itemArr[i];
      parItem = {
        title: subIiem,
        children: [],
      };
      if (_columns.length > 0) {
        let hasParent = false;
        for (let j = 0, l = _columns.length; j < l; j++) {
          if (_columns[j].title === subIiem) {
            _columns = _columns[j].children;
            hasParent = true;
            break;
          }
        }
        if (!hasParent) {
          _columns.push(parItem);
        } else {
          parItem.children = _columns;
        }
      } else {
        _columns.push(parItem);
      }
    }
    parItem.children.push(leafItem);
  } else {
    const leafItem = {
      title: item,
      dataIndex: item,
      key: item,
    };
    if (multiple != undefined && typeof multiple === 'number') {
      if (!isNullOrEmpty(sortInfo[item])) {
        multiple++;
        leafItem.sorter = {
          multiple,
        };
        leafItem.sortOrder = sortInfo[item];
      }
    }
    columns.push(leafItem);
  }
  return multiple;
};

// 处理汇总数据
const parseHuiZongData = (parentKey, huiZongData, summaryData) => {
  if (huiZongData && Array.isArray(huiZongData) && huiZongData.length) {
    const data = huiZongData[0];
    const keys = Object.keys(data);
    if (keys.length) {
      const _item = {};
      for (let j = 0, k = keys.length; j < k; j++) {
        const key = keys[j];
        const curkey = parentKey ? `${parentKey}•${key}` : key;
        if (Array.isArray(data[key])) {
          parseHuiZongData(curkey, data[key], summaryData);
        } else {
          summaryData[curkey] = data[key];
        }
      }
    }
  }
};

export function tableFormat(datasets) {
  let sourceFields = [];
  let realData = []; // 原始数据
  let timeStampData = {}; // 时间类型数据
  let dimensionName = []; // 时间类型数据名称
  const {
    fields,
    conditionOptions,
    fieldNameChainMap,
    type,
    collectdataSetType,
    source,
    huiZongData,
    dimensions,
    conditionData,
    sortInfo = {},
  } = datasets;
  const { xAxis, yAxisProgress, yAxisCondition } = dimensions;
  // 判断是否是多列
  let xAxisArr = [];
  if (xAxis && xAxis.includes('&')) {
    xAxisArr = xAxis.split('&');
  } else {
    xAxisArr = xAxis ? [xAxis] : [];
  }
  // 进度
  let yAxisProgressArr = [];
  if (yAxisProgress && yAxisProgress.includes('&')) {
    yAxisProgressArr = yAxisProgress.split('&');
  } else {
    yAxisProgressArr = yAxisProgress ? [yAxisProgress] : [];
  }
  // 条件项存在多度量
  let yAxisConditionArr = [];
  if (yAxisCondition && yAxisCondition.includes('&')) {
    yAxisConditionArr = yAxisCondition.split('&');
  } else {
    yAxisConditionArr = yAxisCondition ? [yAxisCondition] : [];
  }
  // 排除条件项数据后的名称集合
  let dimensionsMap = [];
  let sourceColumns = [];
  if (xAxisArr.length > 0) {
    dimensionsMap.push(...xAxisArr);
    for (let i = 0, len = xAxisArr.length; i < len; i++) {
      sourceColumns.push(
        xAxisArr[i].indexOf('•') != -1
          ? xAxisArr[i].split('•')[xAxisArr[i].split('•').length - 1]
          : xAxisArr[i],
      );
    }
  }
  if (yAxisProgressArr.length > 0) {
    dimensionsMap.push(...yAxisProgressArr);
    for (let i = 0, len = dimensionsMap.length; i < len; i++) {
      sourceColumns.push(
        dimensionsMap[i].indexOf('•') != -1
          ? dimensionsMap[i].split('•')[dimensionsMap[i].split('•').length - 1]
          : dimensionsMap[i],
      );
    }
  }
  // 将包含子表单的数据拉平，并同时生成表格合并映射体
  const { list: dataList, columnRowSpanMap } = dealDynamicOneData(source, sourceColumns);
  let summaryData = {};

  if (!dataList.length) {
    const columns = [];
    let multiple = undefined;
    if (!(isNullOrEmpty(xAxis) && isNullOrEmpty(yAxisProgress))) {
      for (let i = 0, len = dimensionsMap.length; i < len; i++) {
        const item = dimensionsMap[i];
        parseDimensionsItem(sortInfo, item, columns, multiple);
      }
    }
    return {
      seriesData: [],
      //拖入字段，接口返回空数据，也显示表头数据
      columns: columns,
      columnRowSpanMap,
    };
  }
  let seriesData = [];
  let columns = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
    },
  ];
  // 静态数据就取source数据
  let sourceData = dataList;
  // 只包含维度的数据
  let realDimensionData = [];
  // 动态数据
  if (type !== 'STATIC') {
    sourceFields = { ...fieldNameChainMap?.xAxis, ...fieldNameChainMap?.yAxisProgress };
    const typeNameList =
      Object.keys(collectdataSetType) &&
      Object.keys(collectdataSetType).filter((type) => type === 'TIMESTAMP');
    dimensionName = typeNameList.map((name) => collectdataSetType[name]);
    // 获取时间类型的数据名称
    realData = cloneDeep(dataList);
    // 排除条件项的动态数据
    sourceData = dataList.map((data, index) => {
      let obj = {};
      dimensionsMap.map((name) => {
        obj[name] = data[name];
      });
      return obj;
    });
    // 只包含维度的数据
    realDimensionData = dataList.map((data, index) => {
      let obj = {};
      xAxisArr.map((name) => {
        obj[name] = data[name];
      });
      return obj;
    });
  }
  let _index = 0;
  $each(sourceData, (item, index) => {
    const columnRowSpan = columnRowSpanMap['key'][index];
    _index = columnRowSpan > 0 ? _index + 1 : _index;
    seriesData.push({
      key: index,
      index: _index,
      ...item,
    });
  });
  // parseHuiZongData(undefined, huiZongData, summaryData);
  // 处理汇总：接口返回的数据字段没有嵌套，采用下面的逻辑处理
  if (huiZongData && Array.isArray(huiZongData) && huiZongData.length) {
    const data = huiZongData[0];
    let obj = {};
    dimensionsMap.map((name) => {
      const _name =
        name.indexOf('•') != -1 ? name.split('•')[name.split('•').length - 1] : name;
      obj[name] = data[_name];
    });
    summaryData = obj;
  }
  let multiple = 0;
  $each(sourceData[0], (item, key) => {
    multiple = parseDimensionsItem(sortInfo, key, columns, multiple);
    // let column = {
    //   title: key,
    //   dataIndex: key,
    //   key: key,
    // };
    // if (!isNullOrEmpty(sortInfo[key])) {
    //   multiple++;
    //   column.sorter = {
    //     multiple,
    //   };
    //   column.sortOrder = sortInfo[key];
    // }
    // columns.push(column);
  });
  // 查找时间类型数据
  dimensionName.forEach((name) => {
    const result = realData.map((item) => {
      return { value: item[name] };
    });
    timeStampData[name] = result;
  });
  // 条件项存在
  if (!isEmptyArr(yAxisConditionArr)) {
    yAxisConditionArr.forEach((yItem) => {
      const yConditionData = [];
      dataList.forEach((item) => {
        yConditionData.push({
          value: item[yItem],
        });
      });
      // 根据原始字段名称收集数据
      if (fieldNameChainMap['yAxisCondition'] && fieldNameChainMap['yAxisCondition'][yItem]) {
        conditionData[fieldNameChainMap['yAxisCondition'][yItem]].push(...yConditionData);
      }
    });
  }
  // 处理条件格式
  const componentAttrs = {
    conditionOptions,
    config: {
      sourceFields,
      data: seriesData,
      realData: dataList,
      conditionData, // 条件项数据
    },
    timeStampData,
  };
  // 条件格式后的数据集合
  const tableConditionSetMap = handleDetailTableConditions(componentAttrs);
  return {
    seriesData,
    summaryData,
    columnRowSpanMap,
    columns,
    tableConditionSetMap,
    realDimensionData,
  };
}
